package co.edu.eam.iso.view;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import co.edu.eam.iso.dao.MetricDAO;
import co.edu.eam.iso.enums.ActionEnum;
import co.edu.eam.iso.enums.CharacteristicEnum;
import co.edu.eam.iso.enums.IconEnum;
import co.edu.eam.iso.enums.SubCharacteristicEnum;
import co.edu.eam.iso.evaluator.Metric;

/**
 * Manage metrics window.
 * 
 * @author Giovanny Ramirez Blandon
 * @version 1.0
 */
public class ManageMetrics extends JDialog {
	
	/**
	 * Number of class serialization.
	 */
	private static final long serialVersionUID = 1L;

	private MetricDAO metricDAO;
		
	private DefaultTableModel defaultTableModel;
	
	/**
	 * Content pane.
	 */
	private JPanel contentPane;

	/**
	 * Table containing the metrics.
	 */
	private JTable tblMetrics;
	private JComboBox cbCharacteristics;
	private JComboBox cbSubcharacteristics;
	
	private boolean enabledbuttons;
	private JButton btnEdit;
	private JButton btnDelete;
	
	private CharacteristicEnum characteristicSelected;
	private JButton btnSelect;
	
	private Component parent;
	
	private ActionEnum actionParent;
		
	/**
	 * Create the frame.
	 */
	public ManageMetrics(Component parent, ActionEnum actionParent,
			CharacteristicEnum characteristicSelected) {
		this.actionParent = actionParent;
		this.parent = parent;
		this.characteristicSelected = characteristicSelected;
		metricDAO = new MetricDAO();
		enabledbuttons = false;
		initialize();
		clearTable();
	}
	
	private void initialize() {
		setTitle("ISO 9126-1 - Métricas");
		setBounds(100, 100, 498, 465);
		setLocationRelativeTo(null);
		setModalityType(ModalityType.APPLICATION_MODAL);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setResizable(false);
		setLocationRelativeTo(parent);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(null);		
		contentPane.add(createPanelMetrics(actionParent));
		contentPane.add(createPanelSearchFilters(actionParent));
		setContentPane(contentPane);
		
		JButton btnCancel = new JButton("Cancelar");
		btnCancel.setBounds(385, 405, 90, 25);
		contentPane.add(btnCancel);
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				closeWindow();
			}
		});
	}
	
	private void searchMetrics() {
		if (cbSubcharacteristics.getSelectedIndex() != 0) {
			refreshTable();
			enableActionButtons(false);

			if (defaultTableModel.getRowCount() == 0) {
				JOptionPane.showMessageDialog(this,
						"No existen métricas para la sub-característica seleccionada",
						"Mensaje de información", JOptionPane.INFORMATION_MESSAGE);
			}
		} else {
			JOptionPane.showMessageDialog(this,
					"Debe seleccionar la sub-característica", "Mensaje de error",
					JOptionPane.ERROR_MESSAGE);
		}
	}
	
	private void loadCharacteristics() {
		for (CharacteristicEnum characteristic : CharacteristicEnum.values()) {
			cbCharacteristics.addItem(characteristic);
		}
	}
	
	private void loadSubCharacteristics(int idCharacteristic) {
		for (SubCharacteristicEnum subCharacteristic : SubCharacteristicEnum
				.getByIdCharacteristic(idCharacteristic)) {
			cbSubcharacteristics.addItem(subCharacteristic);
		}
	}

	private void closeWindow() {
		dispose();
	}
	
	private void enableActionButtons(boolean enable) {
		if (ActionEnum.SELECT == actionParent) {
			btnSelect.setEnabled(enable);
		}

		btnEdit.setEnabled(enable);
		btnDelete.setEnabled(enable);
		enabledbuttons = enable;
	}
	
	private void clearTable() {
		defaultTableModel = new DefaultTableModel(null, 
				new String[] { "Código", "Descripci\u00F3n"});	
		tblMetrics.setModel(defaultTableModel);
		tblMetrics.getColumnModel().getColumn(0).setPreferredWidth(60);
		tblMetrics.getColumnModel().getColumn(1).setPreferredWidth(375);
	}
	
	private void refreshTable() {
		clearTable();

		SubCharacteristicEnum subCharacteristic = (SubCharacteristicEnum) cbSubcharacteristics
				.getSelectedItem();

		List<Metric> metrics = metricDAO.searchMetrics(subCharacteristic
				.getId());

		for (Metric metric : metrics) {
			Object[] data = new Object[2];
			data[0] = metric.getId();
			data[1] = metric.getDescription();
			defaultTableModel.addRow(data);
		}
	}
	
	private void createMetric() {
		callModalMetric(null, ActionEnum.CREATE);
	}

	private void editMetric() {
		int row = tblMetrics.getSelectedRow();
		int id = Integer.parseInt(tblMetrics.getValueAt(row, 0).toString());
		Metric metric = metricDAO.findMetric(id);
		callModalMetric(metric, ActionEnum.EDIT);
		refreshTable();
		enableActionButtons(false);
	}
	
	private void selectMetric() {
		int row = tblMetrics.getSelectedRow();
		int id = Integer.parseInt(tblMetrics.getValueAt(row, 0).toString());
		
		sendSelectedMetric(metricDAO.findMetric(id));
		dispose();
	}
	
	private void sendSelectedMetric(Metric metric) {
		EvaluateChrtcs evaluatorWindow = (EvaluateChrtcs) parent;
		evaluatorWindow.setSelectedMetric(metric);
	}
	
	private void callModalMetric(Metric metric, ActionEnum action) {
		ModalMetric modalMetric = new ModalMetric(this, metric, actionParent,
				characteristicSelected);
		modalMetric.setVisible(true);
	}
	
	private ImageIcon getIcon(IconEnum icon) {
		return new ImageIcon(getClass().getResource(icon.getLocation()));
	}
	
	private void deleteMetric() {
		int row = tblMetrics.getSelectedRow();
		int id = Integer.parseInt(tblMetrics.getValueAt(row, 0).toString());
		int option = JOptionPane.showConfirmDialog(this, "¿Está seguro de eliminar la métrica?",
				"Mensaje de advertencia", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
		
		if (option == JOptionPane.YES_OPTION) {
			metricDAO.deleteMetric(id);
			enableActionButtons(false);
			refreshTable();
		}
	}

	private JPanel createPanelSearchFilters(ActionEnum action) {
		JPanel panelSearch = new JPanel();
		panelSearch.setBorder(new TitledBorder(null,
				"Filtros de b\u00FAsqueda", TitledBorder.LEADING,
				TitledBorder.TOP, null, null));
		panelSearch.setBounds(5, 5, 480, 130);
		panelSearch.setLayout(null);
		
		JLabel lblSubcharacteristics = new JLabel("Sub-características");
		lblSubcharacteristics.setBounds(208, 25, 116, 14);
		panelSearch.add(lblSubcharacteristics);

		cbSubcharacteristics = new JComboBox();
		cbSubcharacteristics.addItem("Seleccione");		
		cbSubcharacteristics.setBounds(208, 50, 160, 25);
		lblSubcharacteristics.setLabelFor(cbSubcharacteristics);
		cbSubcharacteristics.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				clearTable();
				enableActionButtons(false);				
			}
		});		
		panelSearch.add(cbSubcharacteristics);

		JLabel lblCharacteristics = new JLabel("Características");
		lblCharacteristics.setBounds(20, 25, 91, 14);
		panelSearch.add(lblCharacteristics);
		
		if (ActionEnum.MANAGE == action) {
			cbCharacteristics = new JComboBox();
			cbCharacteristics.addItem("Seleccione");
			cbCharacteristics.setBounds(20, 50, 160, 25);
			loadCharacteristics();
			cbCharacteristics.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent e) {
					cbSubcharacteristics.removeAllItems();
					cbSubcharacteristics.addItem("Seleccione");		
					if (cbCharacteristics.getSelectedIndex() != 0) {
						loadSubCharacteristics(cbCharacteristics
								.getSelectedIndex());
					}
					
					enableActionButtons(false);
					clearTable();
				}
			});
			panelSearch.add(cbCharacteristics);		
			
		} else if (ActionEnum.SELECT == action) {
			JTextField txtCharacteristic = new JTextField();
			txtCharacteristic.setText(characteristicSelected.toString());
			txtCharacteristic.setEditable(false);
			txtCharacteristic.setBounds(20, 50, 160, 25);
			panelSearch.add(txtCharacteristic);		
			
			loadSubCharacteristics(characteristicSelected.getId());
		}
		
		JButton btnSearch = new JButton("Buscar");
		btnSearch.setBounds(380, 92, 90, 25);
		panelSearch.add(btnSearch);
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				searchMetrics();
			}
		});
		
		return panelSearch;
	}
	
	private JPanel createPanelMetrics(ActionEnum action) {
		JPanel panelMetrics = new JPanel();
		panelMetrics.setBorder(new TitledBorder(null, "M\u00E9tricas",
				TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panelMetrics.setBounds(5, 138, 483, 264);
		panelMetrics.setLayout(null);

		JScrollPane scrollPaneMetrics = new JScrollPane();		
		scrollPaneMetrics.setBounds(51, 25, 419, 225);
		panelMetrics.add(scrollPaneMetrics);

		tblMetrics = new JTable();
		tblMetrics.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tblMetrics.setRowHeight(20);
		clearTable();
		scrollPaneMetrics.setViewportView(tblMetrics);
		tblMetrics.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (!enabledbuttons) {
					enableActionButtons(true);
				}
			}
		});
		
		JButton btnCreate = new JButton();
		btnCreate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				createMetric();
			}
		});
		btnCreate.setToolTipText("Crear");
		btnCreate.setIcon(getIcon(IconEnum.CREATE));
		btnCreate.setBounds(15, 25, 35, 35);
		panelMetrics.add(btnCreate);
		
		btnDelete = new JButton();
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				deleteMetric();
			}
		});
		btnDelete.setEnabled(false);
		btnDelete.setToolTipText("Eliminar");
		btnDelete.setIcon(getIcon(IconEnum.DELETE));
		btnDelete.setBounds(15, 97, 35, 35);
		panelMetrics.add(btnDelete);
		
		btnEdit = new JButton();
		btnEdit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				editMetric();
			}
		});
		btnEdit.setEnabled(false);
		btnEdit.setToolTipText("Editar");
		btnEdit.setIcon(getIcon(IconEnum.MODIFY));
		btnEdit.setBounds(15, 61, 35, 35);
		panelMetrics.add(btnEdit);
		
		if (ActionEnum.SELECT == action) {
			btnSelect = new JButton();
			btnSelect.setEnabled(false);
			btnSelect.setToolTipText("Seleccionar");
			btnSelect.setIcon(getIcon(IconEnum.SELECT));
			btnSelect.setBounds(15, 133, 35, 35);
			btnSelect.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					selectMetric();
				}
			});
			panelMetrics.add(btnSelect);			
		}
		
		return panelMetrics;
	}
}
